package xyz.xtt.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xyz.xtt.admin.entity.TblCarouseImage;
import xyz.xtt.admin.mapper.CarouseImageMapper;
import xyz.xtt.admin.request.CarouseImageRequest;
import xyz.xtt.admin.service.ICarouseImageService;
import xyz.xtt.admin.utils.CosFileUtil;
import xyz.xtt.admin.vo.CarouseImageVo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xugaopeng
 * @date 2024-12-12-11:51
 */
@Service
@Slf4j
@RefreshScope
public class CarouseImageServiceImpl extends ServiceImpl<CarouseImageMapper, TblCarouseImage> implements ICarouseImageService {

    @Autowired
    private CarouseImageMapper carouseImageMapper;

    @Autowired
    private CosFileUtil cosFileUtil;
    /**
     * 滚动图上传oss key
     **/
    private static final String key = "/image/";

    private static final String protocolPre = "https://cdn-nft-sandbox.xtt.xyz";

    private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("(?<=\\.)[^.]+$");


    @Override
    public Page<CarouseImageVo> getList(CarouseImageRequest request) {
        return carouseImageMapper.getList(new Page<CarouseImageVo>(request.getCurrent(), request.getPageSize()), request.getTitle());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCarouseImage(TblCarouseImage carouseImage, MultipartFile file) {
        //上传文件
        File fi = null;
        try {
            fi = covertToFile(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String path = uploadFileToOxx(fi);
        carouseImage.setPicUrl(protocolPre + path);
        log.info("图片上传oss完整路径为：{}", protocolPre + path);
        carouseImageMapper.insert(carouseImage);
        return Boolean.TRUE;
    }

    private File covertToFile(MultipartFile file) throws IOException {
        Matcher matcher = FILE_EXTENSION_PATTERN.matcher(file.getOriginalFilename());
        String suffix = "";
        if (matcher.find()) {
            suffix = matcher.group().toLowerCase();
        }
        FileOutputStream fos = null;
        try {
            File tempFile = File.createTempFile("prefix-", "." + suffix);
            fos = new FileOutputStream(tempFile);
            // 将MultipartFile的内容写入临时文件
            fos.write(file.getBytes());
            return tempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    /**
     * 上传图片至服务器
     *
     * @param file
     * @return String
     * @author xugaopeng
     * @date 2024/12/12 14:53
     **/
    private String uploadFileToOxx(File file) {
        return cosFileUtil.uploadFileToCos(file, key);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delCarouseImages(List<Long> ids) {
        carouseImageMapper.deleteByIds(ids);
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCarouse(TblCarouseImage carouseImage, MultipartFile file) {
        if (file != null && file.getSize() > 0) {
            try {
                carouseImage.setPicUrl(protocolPre + uploadFileToOxx(covertToFile(file)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        carouseImage.setModifyDate(DateUtil.now());
        carouseImageMapper.updateById(carouseImage);
        return Boolean.TRUE;
    }
}
